package week2;

import java.util.Arrays;

public class HaakjesExpressie
{
	private char[] brackets = new char[] {'(', ')', '<', '>', '[', ']', '{', '}'};
	
	//private CharSequence bracketsSequence = CharBuffer.wrap(brackets);
	
	public boolean isCorrectHaakjesExpressie(String s)
	{
		/*if (!s.contains(bracketsSequence))
		{
			return false;
		}*/
		
		MyStack<Character> ms = new MyStack<Character>();
		
		for (char c: s.toCharArray())
		{
			// Get the index of the char in our brackets array.
			int index = Arrays.binarySearch(brackets, c);
			
			// If the char is not an bracket.
			if (index < 0)
			{
				return false;
			}
			
			// Opening bracket.
			if (index % 2 == 0)
			{
				ms.push(c);
			}
			// Closing bracket.
			else
			{
				// Closing bracket match correct opening bracket, for example > matches <.(',
				Character x = ms.peek();
				
				if (x != null && x == brackets[index - 1])
				{
					ms.pop();
				}
				// Else it is a invalid nested bracket sequence.
				else
				{
					return false;
				}
			}
		}
		
		// It was a valid bracket sequence.
		return ms.isEmpty();
	}
	
	public void run()
	{
		String s = "())";
		
		if (isCorrectHaakjesExpressie(s))
		{
			System.out.println("expressie is goed");
		}
		else
		{
			System.out.println("expressie is fout");
		}
	}
	
	public static void main(String[] args)
	{
		HaakjesExpressie he = new HaakjesExpressie();
		
		he.run();
	}
}
